#! /usr/bin/env python
#
# Implement cookbook using pyfitsio
import sys
import os

import ctypes

# Use just the C-types bindings to CFITSIO
from fitsio import cfitsio, pyfitsio

def copy_header(ffin, ffout):

    status = ctypes.c_int()
    morekeys = ctypes.c_int(0)
    cfitsio.fits_copy_hdu(ffin.fptr, ffout.fptr, morekeys, 
                          ctypes.byref(status))
    pyfitsio.check_error(status)

def main():
    '''
    Copy 1st and 3rd HDUs from input file to a new FITS file
    '''

    infilename  = 'atestfil.fit'
    outfilename = 'btestfil.fit'

    # Open input file
    ffin = pyfitsio.open(infilename, mode='r')

    # Create another FITS file
    ffout = pyfitsio.open(outfilename, mode='w', clobber=True)
    
    # Copy primary HDU header from input to ouput file
    copy_header(ffin, ffout)

    # Move to 3rd HDU in the input file
    ffin.move_to_hdu(3)

    # Copy 3rd HDU from input file to the 2nd HDU of output file
    copy_header(ffin, ffout)

    ffout.close()
    ffin.close()

if __name__ == '__main__':
    main()
